<script setup>
import { ref, watch } from "vue";
import { ElMessage, ElLoading } from "element-plus";
// 导入七牛云上传工具
import { uploadToQiniu } from "@/utils/qiniu";
import request from "@/utils/request";

// 接收父组件传递的props
const props = defineProps({
  userInfo: {
    type: Object,
    required: true,
  },
  isViewingOtherUser: {
    type: Boolean,
    default: false,
  },
  isFollowing: {
    type: Boolean,
    default: false,
  },
});

// 定义组件事件
const emit = defineEmits(["update-profile", "toggle-follow"]);

// 控制弹窗显示
const dialogVisible = ref(false);
// 用于编辑的用户信息
const editForm = ref({
  username: "",
  avatar: "",
  bio: "",
});

// 文件上传相关
const avatarUrl = ref("");
const fileInputRef = ref(null);
const avatarFile = ref(null);

// 监听用户信息变化，更新表单数据
watch(
  () => props.userInfo,
  (newValue) => {
    if (newValue) {
      avatarUrl.value = newValue.avatar;
    }
  },
  { immediate: true }
);

function handleEditProfile() {
  // 初始化表单数据
  editForm.value = {
    username: props.userInfo.username,
    avatar: props.userInfo.avatar,
    bio: props.userInfo.bio || "",
  };
  avatarUrl.value = props.userInfo.avatar;
  dialogVisible.value = true;
}

function handleAvatarClick() {
  // 触发文件选择
  fileInputRef.value.click();
}

function handleFileChange(e) {
  const file = e.target.files[0];
  if (!file) return;

  // 验证文件类型
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("请上传图片文件");
    return;
  }

  // 验证文件大小 (限制为2MB)
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error("图片大小不能超过2MB");
    return;
  }

  // 保存文件对象以供后续上传
  avatarFile.value = file;

  // 预览头像
  const reader = new FileReader();
  reader.onload = (event) => {
    avatarUrl.value = event.target.result;
  };
  reader.readAsDataURL(file);
}

async function handleSubmit() {
  // 表单验证
  if (!editForm.value.username.trim()) {
    ElMessage.error("用户名不能为空");
    return;
  }

  // 准备待提交的信息
  const updatedInfo = {
    username: editForm.value.username.trim(),
    bio: editForm.value.bio.trim(),
  };

  // 如果有新头像，需要特殊处理
  if (avatarFile.value) {
    // 创建加载指示器
    const loadingInstance = ElLoading.service({
      lock: true,
      text: "正在上传头像...0%",
      background: "rgba(0, 0, 0, 0.7)",
    });

    try {
      // 上传到七牛云OSS，支持显示上传进度
      const uploadResult = await uploadToQiniu(
        avatarFile.value,
        "avatar",
        (percent) => {
          // 更新加载文本
          loadingInstance.setText(`正在上传头像...${Math.floor(percent)}%`);
        }
      );

      // 关闭加载状态
      loadingInstance.close();

      // 添加头像URL字段
      if (uploadResult && uploadResult.url) {
        updatedInfo.avatar = uploadResult.url;
      }
    } catch (error) {
      ElMessage.error("头像上传失败，请稍后重试");
      console.error("头像上传失败:", error);
      return;
    }
  }
  // 提交更新
  emit("update-profile", updatedInfo);
  dialogVisible.value = false;
  // 重置文件对象
  avatarFile.value = null;
}

function handleCancel() {
  dialogVisible.value = false;
  avatarFile.value = null;
}

// 处理关注/取消关注
function handleFollowAction() {
  emit("toggle-follow");
}
</script>

<template>
  <div class="user-profile">
    <div class="profile-header">
      <div class="avatar-container">
        <img :src="userInfo.avatar" alt="用户头像" class="avatar" />
      </div>
      <div class="user-info">
        <h2 class="username">{{ userInfo.username }}</h2>
        <p class="bio" v-if="userInfo.bio">{{ userInfo.bio }}</p>
        <div class="stats">
          <div class="stat-item">
            <span class="stat-count">{{ userInfo.follows || 0 }}</span>
            <span class="stat-label">关注</span>
          </div>
          <div class="stat-item">
            <span class="stat-count">{{ userInfo.fans || 0 }}</span>
            <span class="stat-label">粉丝</span>
          </div>
        </div>
      </div>
      <div class="actions">
        <!-- 查看他人资料时显示关注/取消关注按钮 -->
        <button
          v-if="isViewingOtherUser"
          class="edit-button"
          @click="handleFollowAction"
        >
          {{ isFollowing ? "取消关注" : "关注" }}
        </button>
        <button v-else class="edit-button" @click="handleEditProfile">
          <span class="edit-icon">✏️</span>
          <span>编辑资料</span>
        </button>
      </div>
    </div>
    <!-- 编辑资料弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑个人资料"
      width="500px"
      destroy-on-close
    >
      <div class="edit-profile-form">
        <div class="avatar-upload">
          <div class="avatar-preview" @click="handleAvatarClick">
            <img :src="avatarUrl" alt="头像预览" />
            <div class="upload-overlay">
              <i class="el-icon-upload"></i>
              <span>更换头像</span>
            </div>
          </div>
          <input
            type="file"
            ref="fileInputRef"
            @change="handleFileChange"
            accept="image/*"
            style="display: none"
          />
        </div>

        <el-form :model="editForm" label-position="top">
          <el-form-item label="用户名">
            <el-input
              v-model="editForm.username"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="个人简介">
            <el-input
              v-model="editForm.bio"
              type="textarea"
              :rows="3"
              maxlength="100"
              show-word-limit
              placeholder="介绍一下你自己吧..."
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.user-profile {
  background-color: #272933;
  padding: 8px 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  border-radius: 16px;
  transition: all 0.3s ease;
}

.profile-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-container {
  position: relative;
}

.avatar {
  width: 90px;
  height: 90px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f8f8f8;
  transition: transform 0.3s ease;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);

  &:hover {
    transform: scale(1.05);
  }
}

.user-info {
  flex: 1;
  color: #ffffff;
}

.username {
  font-size: 1.3rem;
  font-weight: bold;
  margin: 0 0 8px 0;
  background: linear-gradient(45deg, #0096ff, #6c47ff);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.bio {
  margin: 0 0 12px 0;
  font-size: 0.9rem;
  color: #e0e0e0;
  line-height: 1.4;
  max-width: 500px;
}

.stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-count {
  font-weight: bold;
  font-size: 1rem;
  color: #ffffff;
}

.stat-label {
  font-size: 0.9rem;
  color: #99a3a7;
  margin-top: 4px;
}

.actions {
  margin-left: auto;
}

.edit-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 18px;
  background: linear-gradient(45deg, #0096ff, #6c47ff);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 0.95rem;
  font-weight: 500;
  transition: all 0.2s ease;
  box-shadow: 0 2px 8px rgba(0, 150, 255, 0.3);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 150, 255, 0.5);
    background: linear-gradient(45deg, #0077cc, #5535ff);
  }

  &:active {
    transform: translateY(0);
  }

  .edit-icon {
    font-size: 1rem;
  }
}

// 编辑弹窗样式
.edit-profile-form {
  padding: 20px;
}

.avatar-upload {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  border: 3px solid #f0f0f0;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s;
    color: white;

    i {
      font-size: 24px;
      margin-bottom: 5px;
    }

    span {
      font-size: 12px;
    }
  }

  &:hover .upload-overlay {
    opacity: 1;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.follow-button {
  background: linear-gradient(45deg, #0096ff, #6c47ff);
  color: white;
}

.unfollow-button {
  background: #272933;
  border: 1px solid #0096ff;
  color: #0096ff;
}
</style>
